package game.screen;

import game.Constants;
import game.Conversation;
import game.Message;
import game.Person;
import game.communication.Communication;
import game.manager.ConversationManager;
import game.manager.PersonManager;
import game.screen.option.BackOption;
import game.screen.option.ForwardOption;
import game.screen.option.ScreenOption;
import game.util.CommunicationUtil;
import game.util.Util;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;

public class ConversationScreen extends Screen {
	private Conversation conversation;
	private Person sender;
	private Person receiver;

	public ConversationScreen(Conversation conversation) {
		this.conversation = conversation;
		this.sender = PersonManager.getManager().getUser();
		this.receiver = conversation.getOtherParticipant(sender);
	}

	@Override
	protected List<ScreenOption> getOptions() {
		final List<ScreenOption> options = new Vector<ScreenOption>();
		final CommunicationUtil communicationUtil = new CommunicationUtil();
		Collection<Communication> communications = communicationUtil
				.getCommunications(sender, receiver, conversation.getMessages());

		for (final Communication communication : communications) {
			options.add(new ScreenOption(communication.getText()) {

				@Override
				public void select() {
					ConversationManager.getManager().sendMessage(sender,
							receiver, communication, new Date());
					ConversationScreen.this.refreshScreen();
				}
			});

		}
		options.add(new BackOption());
		options.add(new ForwardOption());
		return options;
	}

	@Override
	public void print() {
		if (!this.printed) {
			this.printed = true;
			// Print the title
			printTitle();
			// Print previous messages
			printMessages();
			// Print the options
			printOptions();
			// Let the user choose an option
			promptInput();
		}
	}

	private void printMessages() {
		for (Message message : conversation.getMessages()) {
			printMessage(message);
		}
	}

	private void printMessage(Message message) {
		String firstName = message.getSender().getFirstName();
		String body = message.getCommunication().getText();
		Util.print("/-----------------------------------------\\\n");
		Util.print(Util.getShortDate(message.getTime()) + "\n");
		Util.print("[" + firstName + "]: " + body + "\n");
		Util.print("\\-----------------------------------------/\n");
	}

	@Override
	public String getTitle() {
		return receiver.getFullName() + " - " + Constants.MESSAGES;
	}

	@Override
	public void draw() {
	}
}
